from stark.service.v1 import StarkModelForm, BootStrapForm
from django.db.models import CharField, Value
from django.db.models.functions import Concat

from ..models import House


class HouseModelForm(BootStrapForm, StarkModelForm):
    class Meta:
        model = House
        # 排除以下字段不显示在表单中：创建时间、更新时间、操作员和创建者
        exclude = ['created_at', 'updated_at', "operator"]
    
    def __init__(self, request, *args, **kwargs):
        self.request = request
        # 调用父类的初始化方法
        super().__init__(*args, **kwargs)
        if not request or not hasattr(request, 'tracer') or not hasattr(request.tracer, 'user'):
            return
        
        # 获取当前用户和角色信息
        user = request.tracer.user
        roles = request.tracer.roles
        # 使用更灵活的角色检查 - 检查是否具有管理员角色
        if roles.filter(title="管理员").exists():
            return
        if roles.filter(title="房东").exists():
            self.fields["landlord"].choices = [(user.id, user.name)]
            self.fields['created_by'].initial = user
   
        self.fields["operator"].choices = [(user.id, user.name)]


